package com.webapps.tvprogram.data.local;

import java.io.File;
import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.webapps.tvprogram.R;
import com.webapps.tvprogram.ui.MainActivity;
import com.webapps.tvprogram.utils.GlobalInfo;

public class LocalResourcesHandler {

    public Bitmap getBitmapFromResource(String programName) {
        File f = new File(GlobalInfo.PATH_TO_IMAGES);
        File[] allFiles = f.listFiles();
        String fileName = null;
        for (int i = 0; i < allFiles.length; i++) {
            if (allFiles[i].getName().contains(programName)) {
                fileName = allFiles[i].getName();
            }
        }
        if (fileName != null) {
            Bitmap b = BitmapFactory.decodeFile(GlobalInfo.PATH_TO_IMAGES + fileName);
            // TODO b.eraseColor(Color.TRANSPARENT);
            return b;
        } else {
            return null;
        }
    }

    public Bitmap createUnknownBitmap() {
        // TODO check if bitmap was downloaded
        // if ! downloaded
        Bitmap bmp = BitmapFactory.decodeResource(MainActivity.getInstance().getResources(), R.drawable.question_mark);
        Bitmap returnBitmap = Bitmap.createScaledBitmap(bmp, GlobalInfo.programIconSize, GlobalInfo.programIconSize,
                false);
        bmp.recycle();
        bmp = null;
        return returnBitmap;
    }

    public void saveBitmapToFile(String stationName, Bitmap bmp, String extension) {
        try {
            if (bmp == null) {
                Log.e("WebRetreiver", "downloadedImage == null");
                return;
            }
            File dir = new File(GlobalInfo.PATH_TO_IMAGES);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File f = new File(GlobalInfo.PATH_TO_IMAGES + stationName + "." + extension);
            if (!f.exists()) {
                f.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(f);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
